const fs = require('fs')

const studentsInfoJson = './json/studentsInfo.json'

exports.getIndexJsonData = (callback) => {
  fs.readFile(studentsInfoJson, (err, data) => {
    if (err) {
      return callback(err)
    }
    callback(null, JSON.parse(data))
  })
}

exports.submitAddPostData = (formData, callback) => {
  fs.readFile(studentsInfoJson, 'utf-8', (err, data) => {
    if (err) {
      return callback(err)
    }

    const students = [...JSON.parse(data)]
    formData.id = students.length + 1
    students.push(formData)

    fs.writeFile(studentsInfoJson, JSON.stringify(students), (err) => {
      if (err) {
        return callback(err)
      }

    })
  })
}

exports.submitEditPostData = (formData, callback) => {
  fs.readFile(studentsInfoJson, 'utf-8', (err, data) => {
    if (err) {
      return callback(err)
    }

    const students = [...JSON.parse(data)]
    students.splice(students.findIndex(item => parseInt(item.id) === parseInt(formData.id)), 1, formData)

    fs.writeFile(studentsInfoJson, JSON.stringify(students), (err) => {
      if (err) {
        return callback(err)
      }

    })
  })
}

exports.writeDataInEdit = (id, callback) => {
  fs.readFile(studentsInfoJson, 'utf-8', (err, data) => {
    if (err) {
      return callback(err)
    }

    const parseData = JSON.parse(data)
    const selData = parseData.find(item => ~~item.id === ~~id)

    callback(null, selData)
  })
}

exports.deleteData = (id, callback) => {
  fs.readFile(studentsInfoJson, 'utf-8', (err, data) => {
    if (err) {
      return callback(err)
    }

    const parseData = JSON.parse(data)
    parseData.splice(parseData.findIndex(item => ~~item.id === ~~id), 1)

    fs.writeFile(studentsInfoJson, JSON.stringify(parseData), (err) => {
      if (err) {
        return callback(err)
      }
    })
    callback(null)
  })
}